const dayjs = require("dayjs")
const {writeFileSync, readFileSync, statSync} = require("fs")

const {join} = require("path")

module.exports = class DbLog {
    constructor(err) {
        this.err = err
    }

    static setLog(err) {
        //构造错误对象
        let msg = '未知错误';
        let key = err ? Object.keys(err) : void 0

        let object = {
            err: key.find(item => item == 'code') ? err.code : msg,
            time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        //构造json数据源
        let filepath = join(__dirname, '..', '/log', 'dblog.json')
        //读取json数据源
        let dbLogByJson = JSON.parse(readFileSync(filepath, {encoding: 'utf8',}))
        //在头部插入错误对象
        dbLogByJson.unshift(object)
        // 将数对象写回数据源
        writeFileSync(filepath, JSON.stringify(dbLogByJson), {encoding: 'utf8'})
        console.log('已记录 ' + filepath)
    }

    static getLog() {
        //构造json数据源
        let filepath = join(__dirname, '..', '/log', 'dblog.json')
        return JSON.parse(readFileSync(filepath, {encoding: 'utf8',}))
    }
}








